﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Project.Yan.Net.Redis.RedisBase
{
    public abstract class BaseCacheHelper<T,TKey>
    {
        protected abstract IRedisRepository RedisRepository { get; }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<T> GetData(TKey key)
        {
            var cacheKey = GetCacheKeyFromObjKey(key);
            //如果内存缓存中没有，则从Redis中获取
            var value = await RedisRepository.GetAsync<T>(cacheKey);
            if (value != null)
            {
                return value;
            }
            //如果Redis中也没有，则构建数据并存入Redis
            var obj = await BuildDataByDb(key);
            if (obj != null)
            {
                await RedisRepository.SetAsync(cacheKey, obj, TimeSpan.FromDays(7));
            }
            return obj;
        }
        /// <summary>
        /// 数据库重建
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        protected abstract Task<T> BuildDataByDb(TKey key);
        /// <summary>
        /// 获取缓存Key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected abstract string GetCacheKeyFromObjKey(TKey key);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="keys"></param>
        /// <returns></returns>
       // protected abstract Task<Dictionary<string, T>> BuildDataListByDb(params string[] keys);
        ///// <summary>
        ///// 批量获取数据
        ///// </summary>
        ///// <param name="keys">键列表</param>
        ///// <returns>数据列表</returns>
        //public async Task<List<T>> GetDataBatch(List<string> keys)
        //{
        //    // 从Redis中批量获取
        //    var values = await RedisRepository.GetsAsync<T>(keys);
        //    var result = new List<T>();

        //    // 检查哪些键没有在Redis中找到对应的数据
        //    var keysToBuild = values.Where(x => x.Value == null).Select(d=>d.Key).ToArray();

        //    if (keysToBuild.Any())
        //    {
        //       var dbList=await BuildDataListByDb(keysToBuild);
        //        // 构建缺失的数据并存入Redis
        //        foreach (var item in dbList)
        //        {
        //            values[item.Key] = item.Value;
        //            // 假设这里有一个方法可以将构建的数据存入Redis
        //            await RedisRepository.SetStringAsync(item.Key, System.Text.Json.JsonSerializer.Serialize(item.Value),TimeSpan.FromDays(7));
        //        }

        //    }
        //    return values.Select(x => x.Value).ToList();
        //}

    }
}
